package com.fast.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.io.ClassPathResource;

import java.io.InputStream;
import java.util.Properties;

@Slf4j
@Configuration
public class EnvPostProcessor implements EnvironmentPostProcessor {
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        try {
            Properties properties = ymlParse("shaman-config/dynamicpool.yml");
            PropertiesPropertySource propertySource = new PropertiesPropertySource("dynamicpool.properties", properties);
            environment.getPropertySources().addLast(propertySource);
            log.info("====EnvPostProcessor加载外部配置文件完毕====");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Properties ymlParse(String filepath) {
        YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
        yamlPropertiesFactoryBean.setResources(new ClassPathResource(filepath));
        return yamlPropertiesFactoryBean.getObject();
    }

    public Properties propertiesParse(String filepath) {
        try (InputStream input = new ClassPathResource(filepath).getInputStream();) {
            Properties properties = new Properties();
            properties.load(input);
            return properties;
        } catch (Exception e) {
          log.error(e.getMessage(),e);
        }
        return null;
    }
}
